package net.jsoft.platform.core.util.file;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
import java.util.Base64.Encoder;

public class FileBase64Utils
{
    /**
     * 将文件转成base64 字符串
     * @param path文件路径
     * @return  * 
     * @throws Exception
     */
    public static String encodeBase64File(InputStream in) throws Exception
    {
        byte[] data = null;
        // 读取图片字节数组
        try
        {
            data = new byte[in.available()];
            in.read(data);

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            in.close();
        }

        // 对字节数组Base64编码
        Encoder encoder = Base64.getEncoder();// = new BASE64Encoder();
        return encoder.encodeToString(data);// 返回Base64编码过的字节数组字符串
    }

    /**
     * 将base64字符解码保存文件
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static InputStream decoderBase64File(String base64Code) throws Exception
    {
        byte[] buffer = Base64.getDecoder().decode(base64Code);
        return new ByteArrayInputStream(buffer);
    }
}
